﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using DeJC.DAL.Model;

namespace DeJC.DAL.Repository {
    public abstract class RepositoryBase<T> where T:class {
        internal TheListEntities _dataContext;
        internal DbSet<T> _dbset;
        public RepositoryBase(TheListEntities context) {
            this._dataContext=context;
            this._dbset=context.Set<T>();
        }
        public virtual List<T> Get(
            Expression<Func<T, bool>> filter=null,
            Func<IQueryable<T>, IOrderedQueryable<T>> orderBy=null,
            string includeProperties="") {
            IQueryable<T> query=_dbset;

            if(filter!=null) {
                query=query.Where(filter);
            }

            foreach(var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) {
                query=query.Include(includeProperty);
            }

            if(orderBy!=null) {
                return orderBy(query).ToList();
            }
            else {
                return query.ToList();
            }
        }

        public virtual void Add(T entity) {
            _dbset.Add(entity);
        }
        public virtual void Update(T entity)
        {
            _dbset.Attach(entity);
            _dataContext.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Delete(T entity) {
            _dbset.Remove(entity);
        }
        public virtual void Delete(Expression<Func<T, bool>> where) {
            IEnumerable<T> objects=_dbset.Where<T>(where).AsEnumerable();
            foreach(T obj in objects)
                _dbset.Remove(obj);
        }
        public virtual T GetById(long id) {
            return _dbset.Find(id);
        }
        public virtual T GetById(string id) {
            return _dbset.Find(id);
        }
        public virtual IEnumerable<T> GetAll() {
            return _dbset.ToList();
        }
        public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where) {
            return _dbset.Where(where).ToList();
        }
        public T Get(Expression<Func<T, bool>> where) {
            return _dbset.Where(where).FirstOrDefault<T>();
        }
    }
}
